package xmlpopuler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 * XMLPopuler
 *
 * @author olo
 * XmlPopuler creates XML tree based on txt source file.
 */
public class XMLPopuler {
    
    private static Document doc;
    private static Element root;
    private static final String SOURCE_FILE_PATH = "C:\\dev\\temp\\list.txt";
    private static final String OUTPUT_FILE_PATH = "C:\\dev\\temp\\result.xml";
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            //get source data
            Scanner in = new Scanner(new FileReader(SOURCE_FILE_PATH));
            //create document frame with root node
            createDocumentFrame();
            
            /*
             * This block is designed to be edited. It reads all lines in source
             * file and generates nodes in XML doc.
             */
            //loop source data
            while (in.hasNext()) {
                //get all values in line (i.e. colon delimited)
                String line = in.next();
                String[] elements = line.split(":");

                //create nodes from elements (make sure to create proper tree)
                //i.e. node2 is child of node3 - if you want to add something to created element take object returned from addNode method
                //
                addNode("node1", elements[0], root);
                Element node3 = addNode("node3", "", root);
                node3.setAttribute("attr1", elements[2]);
                node3.setAttribute("attr2", elements[0]);
                addNode("node2", elements[1], node3);
            }

            //generate file
            generateFile();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLPopuler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(XMLPopuler.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    //<editor-fold defaultstate="collapsed" desc="private methods">
    private static void createDocumentFrame() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.newDocument();
            root = doc.createElement("root");
            doc.appendChild(root);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLPopuler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private static void generateFile() {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(OUTPUT_FILE_PATH));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("File saved!");
        } catch (TransformerException ex) {
            Logger.getLogger(XMLPopuler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private static Element addNode(String name, String text, Element parent) {
        //create child
        Element child = doc.createElement(name);
        Text textNode = doc.createTextNode(text);
        child.appendChild(textNode);
        //append child
        parent.appendChild(child);
        return child;
    }//</editor-fold>
}

